package nl.borchef.map_2d_game;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class game_view extends SurfaceView implements SurfaceHolder.Callback, OnTouchListener {
	// start game_view class
	public static final int STATE_READY = 0;
	public static final int STATE_RUNNING = 1;
	public static final int STATE_PAUSE = 2;
	private game_thread mo_thread = null;
	private Context mo_context;
	private game mo_game;

	// game_view constructor
	public game_view(Context context) {
		super(context);
		mo_context = context;
		mo_game = new game(context);
	    //Log.d(this.getClass().getName(), "class created");
		// register our interest in hearing about changes to our surface
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		setOnTouchListener(this);
	}

	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		if( mo_thread != null ){
			mo_thread.pause(!hasWindowFocus);
		}
		super.onWindowFocusChanged(hasWindowFocus);
	}

	@Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        //Log.d(this.getClass().getName(), "surface changed");
		if( mo_thread != null ){
			mo_thread.set_surface_size( width, height );
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
        // start the thread 
        //Log.d(this.getClass().getName(), "surface created");
		// create thread only; it's started in surfaceCreated()
		mo_thread = new game_thread(holder, mo_context, new Handler() {
			@Override
			public void handleMessage(Message m) {
		        //Log.d(this.getClass().getName(), "handled message" + m.getData().getString("text"));
			}
		}, mo_game);
		mo_thread.start();
		mo_thread.surface_ready(true);
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
        //Log.d(this.getClass().getName(), "surface destroyed");
		if( mo_thread != null ){
	        mo_thread.surface_ready(false);
	        mo_thread.save_stop();
	        boolean retry = true;
	        while (retry) {
	            try {
	            	mo_thread.join();
	                retry = false;
	            } catch (InterruptedException e) {
	            }
	        }
	        mo_thread = null;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
        //Log.d(this.getClass().getName(), "touched x=" + String.format("%f y=", event.getX() ) + String.format("%f", event.getY() ));
        mo_game.touched(event.getX(),event.getY());
        return false;
	}
} 
